import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { message } from 'ant-design-vue'
import router from '@/router'
import { login, logout } from '@/api/user/authController'
import { getUser } from '@/api/user/sysUserController'


// 使用新的 API 类型定义
type LoginResponseData = UserService.LoginVO
type ApiResponse<T> = UserService.Result

export interface UserInfo {
  id: number
  username: string
  email?: string
  role: 'student' | 'auditor' | 'merchant' | 'admin' // 四个角色，auditor替换teacher
  name: string
  avatar?: string
  filePath?: string // 添加头像文件路径
  institutionId?: number
  institutionName?: string
  learningTags?: string[] // 学习标签
  permissions?: string[]
  hasTag?: boolean // 是否已选择标签
  forcePasswordChange?: boolean // 是否强制修改密码
}

export interface Institution {
  id: number
  name: string
  code: string
  description?: string
}

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string>('')
  const userInfo = ref<UserInfo | null>(null)
  const institutions = ref<Institution[]>([])
  const currentInstitution = ref<Institution | null>(null)
  const loading = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const isStudent = computed(() => userInfo.value?.role === 'student')
  const isAuditor = computed(() => userInfo.value?.role === 'auditor') // 审核员
  const isMerchant = computed(() => userInfo.value?.role === 'merchant')
  const isAdmin = computed(() => userInfo.value?.role === 'admin')
  const userRole = computed(() => userInfo.value?.role || 'guest')

  // 获取机构列表
  const fetchInstitutions = async () => {
    try {
      // 模拟API调用
      const mockInstitutions: Institution[] = [
        { id: 1, name: '智教易购学院', code: 'zhijiao', description: '专注于在线教育的领先机构' },
        { id: 2, name: '未来科技学院', code: 'futuretech', description: '前沿科技教育机构' },
        { id: 3, name: '智慧学习中心', code: 'smartlearn', description: '智能化学习平台' }
      ]
      institutions.value = mockInstitutions
      return mockInstitutions
    } catch (error) {
      console.error('获取机构列表失败:', error)
      return []
    }
  }

  
  // 统一登录方法
  const loginUser = async (credentials: { username: string; password: string; captcha?: string; captchaKey?: string }) => {
    loading.value = true
    try {
      // 调用后端登录接口
      const loginRequest = {
        username: credentials.username,
        password: credentials.password,
        captcha: credentials.captcha,
        captchaKey: credentials.captchaKey
      }

      const response = await login(loginRequest)
      const responseData = response as unknown as ApiResponse<LoginResponseData>
      
      if (responseData.code === '00000' && responseData.data) {
        const { accessToken, userId, username, roleCodes, hasTag } = responseData.data
        
        // 根据角色代码确定用户角色
        let role: 'student' | 'auditor' | 'merchant' | 'admin' = 'student'
        if (roleCodes.includes('admin')) {
          role = 'admin'
        } else if (roleCodes.includes('auditor')) {
          role = 'auditor'
        } else if (roleCodes.includes('merchant')) {
          role = 'merchant'
        }

        // 构建用户信息
        const userInfoData: UserInfo = {
          id: userId,
          username: username,
          role: role,
          name: username, // 后端返回的用户名作为显示名称
          permissions: roleCodes,
          hasTag: hasTag // 添加hasTag字段
        }

        // 保存认证信息
        token.value = accessToken
        userInfo.value = userInfoData

        // 保存到本地存储
        localStorage.setItem('token', accessToken)
        localStorage.setItem('userInfo', JSON.stringify(userInfoData))

        // 获取完整的用户信息（包括头像等）
        try {
          const userResponse = await getUser()
          if ((userResponse as any).code === '00000' && (userResponse as any).data) {
            const fullUserData = (userResponse as any).data
            // 更新用户信息，保留原有的角色信息和hasTag
            const updatedUserInfo = {
              ...userInfoData,
              email: fullUserData.email,
              filePath: fullUserData.filePath,
              nickname: fullUserData.nickname,
              sex: fullUserData.sex,
              phone: fullUserData.phone,
              hasTag: hasTag // 确保hasTag字段被保留
            }
            userInfo.value = updatedUserInfo
            localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
          }
        } catch (error) {
          console.error('获取完整用户信息失败:', error)
          // 不影响登录流程，继续使用基本用户信息
        }

        // 移除冗余的登录成功消息，让调用方处理

        // 不在这里跳转页面，让调用方决定如何处理
        // await redirectByRole(role)

        return true
      } else {
        throw new Error(responseData.msg || '登录失败')
      }
    } catch (error: any) {
      console.error('登录错误:', error)
      // 不在这里显示错误消息，让调用方处理
      // message.error(error.message || '登录失败，请重试')
      throw error // 重新抛出错误，让调用方处理
    } finally {
      loading.value = false
    }
  }

  // 根据角色跳转
  const redirectByRole = async (role: string) => {
    switch (role) {
      case 'student':
        // 学员登录后留在首页
        await router.push('/')
        break
      case 'auditor':
        await router.push('/auditor')
        break
      case 'merchant':
        await router.push('/merchant')
        break
      case 'admin':
        await router.push('/admin')
        break
      default:
        await router.push('/')
    }
  }

  // 切换机构
  const switchInstitution = async (institutionId: number) => {
    try {
      const institution = institutions.value.find(i => i.id === institutionId)
      if (!institution) {
        throw new Error('机构不存在')
      }

      // 模拟切换机构API调用
      currentInstitution.value = institution
      localStorage.setItem('currentInstitution', JSON.stringify(institution))
      message.success(`已切换到 ${institution.name}`)
      return true
    } catch (error: any) {
      message.error(error.message || '切换机构失败')
      return false
    }
  }

  // 登出
  const logoutUser = async () => {
    try {
      // 调用后端登出接口
      await logout()
    } catch (error) {
      console.error('登出接口调用失败:', error)
    } finally {
      // 无论后端接口是否成功，都清除本地状态
      token.value = ''
      userInfo.value = null
      currentInstitution.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('currentInstitution')
      
      message.success('已退出登录')
      
      // 强制跳转到首页，确保用户退出后回到首页
      await router.push('/')
    }
  }

  // 检查权限
  const hasPermission = (permission: string) => {
    if (!userInfo.value?.permissions) return false
    return userInfo.value.permissions.includes(permission)
  }

  // 初始化认证状态
  const initAuth = () => {
    const savedToken = localStorage.getItem('token')
    const savedUserInfo = localStorage.getItem('userInfo')
    const savedInstitution = localStorage.getItem('currentInstitution')

    if (savedToken && savedUserInfo) {
      try {
        token.value = savedToken
        userInfo.value = JSON.parse(savedUserInfo)
        if (savedInstitution) {
          currentInstitution.value = JSON.parse(savedInstitution)
        }
        
        // 如果有token但没有完整的用户信息，尝试获取
        if (userInfo.value && !userInfo.value.filePath) {
          refreshUserInfo()
        }
      } catch (error) {
        console.error('初始化认证状态失败:', error)
        logout()
      }
    }
  }

  // 刷新用户信息
  const refreshUserInfo = async () => {
    if (!token.value) return

    try {
      const userResponse = await getUser()
      if ((userResponse as any).code === '00000' && (userResponse as any).data) {
        const fullUserData = (userResponse as any).data
        // 更新用户信息，保留原有的角色信息
        if (userInfo.value) {
          const updatedUserInfo = {
            ...userInfo.value,
            email: fullUserData.email,
            filePath: fullUserData.filePath,
            avatar: fullUserData.avatar || fullUserData.filePath, // 确保头像字段被正确设置
            nickname: fullUserData.nickname,
            sex: fullUserData.sex,
            phone: fullUserData.phone
          }
          userInfo.value = updatedUserInfo
          localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
          console.log('用户信息刷新成功，头像路径:', updatedUserInfo.filePath)
        }
      }
    } catch (error) {
      console.error('刷新用户信息失败:', error)
      throw error // 重新抛出错误，让调用方知道刷新失败
    }
  }

  // 更新用户信息
  const updateUserInfo = (updates: Partial<UserInfo>) => {
    if (userInfo.value) {
      userInfo.value = { ...userInfo.value, ...updates }
      // 保存到本地存储
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }
  }

  return {
    // 状态
    token,
    userInfo,
    institutions,
    currentInstitution,
    loading,
    
    // 计算属性
    isLoggedIn,
    isStudent,
    isAuditor,
    isMerchant,
    isAdmin,
    userRole,
    
    // 方法
    login: loginUser,
    logout: logoutUser,
    switchInstitution,
    hasPermission,
    initAuth,
    refreshUserInfo,
    updateUserInfo,
    fetchInstitutions
  }
})
